﻿using System;
using System.Linq;
using TaskManager.Domain.BusinessObjects;

namespace TaskManager.Domain.Services
{
    /// <summary>
    /// Implements validation rules for <see cref="Project"/>
    /// </summary>
    internal static class ProjectValidationRules
    {
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ProjectValidationRules));

        /// <summary>
        /// Checks if project can be safely deleted
        /// </summary>
        /// <param name="project">Project</param>
        /// <returns>Pair where first element is validation result and second (optional) contains description why validation was failed</returns>
        public static Tuple<bool,string> PermitDelete(Project project)
        {
            return PermitDelete(project, "delete");
        }

        /// <summary>
        /// Checks if project can be safely closed
        /// </summary>
        /// <param name="project">Project</param>
        /// <returns>Pair where first element is validation result and second (optional) contains description why validation was failed</returns>
        public static Tuple<bool, string> PermitClose(Project project)
        {
            return PermitDelete(project, "close");
        }

        private static Tuple<bool, string> PermitDelete(Project project, string operation)
        {
            int notClosedTaskCount = project.Tasks.Count(task => task.State != TaskState.Finished);

            if (notClosedTaskCount != 0)
            {
                string message = string.Format("unable to {0} the project.There are {1} task(s) in progress", operation, notClosedTaskCount);

                if(Log.IsInfoEnabled) Log.Info(message);

                return new Tuple<bool, string>(false, message);
            }

            return new Tuple<bool, string>(true, string.Empty);
        }
    }
}